using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;

/// <summary>
/// Summary description for UserHelper
/// </summary>
public static class UserHelper
{

    public static int GetUserId(string username)
    {
        string sql = "SELECT ID FROM [Player] WHERE User_name = ?";
        OleDbConnection cn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        cn.Open();
        OleDbCommand cm = new OleDbCommand(sql, cn);
        cm.Parameters.Add("User_name", OleDbType.VarWChar).Value = username;

        int userId = -1;

        try
        {
            OleDbDataReader reader = cm.ExecuteReader();

            while (reader.Read())
            {
                userId = (int) reader["ID"];
            }
            reader.Close();
        }
        finally
        {
            cn.Close();
        }

        if (userId == -1)
            throw new Exception(string.Format("Can't find user {0} in the database.", username));

        return userId;
    }

    public static string GetUserName(int id)
    {
        string sql = "SELECT User_name FROM [Player] WHERE ID = ?";
        OleDbConnection cn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        cn.Open();
        OleDbCommand cm = new OleDbCommand(sql, cn);
        cm.Parameters.Add("ID", OleDbType.Integer).Value = id;

        string userName = null;

        try
        {
            OleDbDataReader reader = cm.ExecuteReader();

            while (reader.Read())
            {
                userName = (string)reader["User_name"];
            }
            reader.Close();
        }
        finally
        {
            cn.Close();
        }

        if (string.IsNullOrEmpty( userName))
            throw new Exception(string.Format("Can't find user with id {0} in the database.", id));

        return userName;
    }
}
